﻿require( '$d/css/common.less' );
require( './style.less' );
define( [
	'jquery',
	'require',
	'header',
	'indusCategory',
	'constants',
	'echarts',
	'message',
	'bigwe_utils',
	'api'
], function( $, require ) {
	var fieldCode = require( 'indusCategory' ),
		constants = require( 'constants' ),
		echarts = require( 'echarts' ),
		ShowTitleMessage = require( 'message' ),
		showTime = ShowTitleMessage.showTime,
		bu = require( 'bigwe_utils' ),
		getUrlParam = bu.getUrlParam,
		BIGWE_API = require( 'api' ),
		thisApis = BIGWE_API.TITLE_DIAGNOSE;
	//行业选项start
	var fjid = '';
	for ( var key in fieldCode ) {
		if ( key.length == 4 ) {
			fjid = key;
			if ( key == '0215' ) {
				var str = '<li class="' + key + '"><span class="field-title-choice">' + fieldCode[ key ] + '</span></li>';
			} else {
				var str = '<li class="' + key + '"><div class="industry_cate"><span class="field-title">' + fieldCode[ key ] + '</span></div><div class="industry_list clearfix"></div></li>';
			}
			$( '.fenlei_more>ul' ).append( str );
		}
		if ( key.length == 6 ) {
			var str = '<span _value="' + key + '" class="field-title-choice">' + fieldCode[ key ] + '</span>';
			$( '.' + fjid + ' .industry_list' ).append( str );
		}
	}
	$( '#diag_search .button' ).click( function( e ) {
		e.stopPropagation();
		$( '#diag_search .fenlei_more' ).slideDown();
	} );
	$( '.fenlei_more' ).on( 'click', '.industry_list span', function( e ) {
		e.stopPropagation();
		var _val = $( this ).text();
		var _property = $( this ).attr( '_value' )
		var _title = $( this ).parent( '.industry_list' ).siblings( '.industry_cate' ).find( 'span' ).text();
		$( this ).parents( '.fenlei_more' ).siblings( '.button' ).html( '<span class="' + _property + '">' + _title + '-' + _val + '</span>' );
		$( this ).parents( '.fenlei_more' ).slideUp();
	} );
	$( '.diagnose_banner' ).click( function() {
		$( '#diag_search .fenlei_more' ).slideUp();
	} );
	$( '.fenlei_more' ).mouseleave( function() {
		$( this ).slideUp();
	} );
	//行业选项end
	//banner波浪start
	var wave = document.getElementById( 'wave' );
	var wave_ctx = wave.getContext( '2d' );
	var wave_color = [ "rgba(255,255,255,0.06)", "rgba(255,255,255,0.1)", "rgba(255,255,255,0.14)" ];
	var step = 0;
	var requestAnimFrame = ( function() {
		return window.requestAnimationFrame ||
			window.webkitRequestAnimationFrame ||
			window.mozRequestAnimationFrame ||
			function( callback ) {
				window.setTimeout( callback, 1000 / 60 );
			};
	} )();

	function loop() {
		wave_ctx.clearRect( 0, 0, wave.width, wave.height );
		step++;
		//画3个不同颜色的矩形
		for ( var j = wave_color.length - 1; j >= 0; j-- ) {
			wave_ctx.fillStyle = wave_color[ j ];
			//每个矩形的角度都不同，每个之间相差45度
			var angle = ( step + j * 45 ) * Math.PI / 180;
			var deltaHeight = Math.sin( angle ) * 50;
			var deltaHeightRight = Math.cos( angle ) * 50;
			wave_ctx.beginPath();
			wave_ctx.moveTo( 0, wave.height / 2 + deltaHeight );
			wave_ctx.bezierCurveTo( wave.width / 2, wave.height / 2 + deltaHeight - 50, wave.width / 2, wave.height / 2 + deltaHeightRight - 50, wave.width, wave.height / 2 + deltaHeightRight );
			wave_ctx.lineTo( wave.width, wave.height );
			wave_ctx.lineTo( 0, wave.height );
			wave_ctx.lineTo( 0, wave.height / 2 + deltaHeight );
			wave_ctx.closePath();
			wave_ctx.fill();
		}
		requestAnimFrame( loop );
	}
	loop();
	//banner波浪end
	
	//波浪进度条start
	var ctx;
	var waveImage;
	var canvasWidth;
	var canvasHeight;
	var needAnimate = false;
	var Schedule = {
		init: function() {
			var canvas = document.getElementById( 'Schedule_wave' );
			canvasWidth = canvas.width;
			canvasHeight = canvas.height;
			if ( !canvas.getContext ) return;
			ctx = canvas.getContext( '2d' );
			ctx.fillStyle = "#fff";
		},
		animate: function( Schedule_val ) {
			var waveX = 0;
			var waveY = 0;
			var waveX_min = -203;
			var waveY_max = canvasHeight * Schedule_val;
			var ratio = 0;
			var score = 0;
			waveImage = new Image();

			if ( Schedule_val < 0.6 ) {
				waveImage.src = constants.resPath + '/images/titlediagnose/wave_red.png';
			} else if ( Schedule_val >= 1 ) {
				waveImage.src = constants.resPath + '/images/titlediagnose/wave_green.png';
			} else {
				waveImage.src = constants.resPath + '/images/titlediagnose/wave_blue.png';
			}

			function loop() {
				ctx.clearRect( 0, 0, canvasWidth, canvasHeight );
				if ( !needAnimate ) return;
				if ( waveY < waveY_max ) waveY += 1;
				
				
				
				if ( waveX < waveX_min ) waveX = 0;
				else waveX -= 1.5;
				ctx.globalCompositeOperation = 'source-over';
				ctx.beginPath();
				ctx.arc( canvasWidth / 2, canvasHeight / 2, canvasHeight / 2, 0, Math.PI * 2, true );
				ctx.closePath();
				ctx.fill();
				ctx.globalCompositeOperation = 'source-in';
				if ( waveY >= canvasHeight ) {
					ctx.drawImage( waveImage, waveX, -25 );
				} else {
					ctx.drawImage( waveImage, waveX, canvasHeight - waveY );
				}

				requestAnimFrame( loop );
			}
			loop();
			function score_val(){
				console.log(waveY)
				ratio = waveY / canvasHeight;
				score = ratio * 100;
				$( '#score' ).text( score.toFixed( 0 ) )
				if(ratio<Schedule_val){
					requestAnimFrame( score_val );
				}
				
			}
			score_val();
		},
		start: function( Schedule_val ) {
			needAnimate = true;
			if ( needAnimate ) {
				Schedule.animate( Schedule_val );
				$( '#Schedule,#Schedule_wave,#score' ).removeClass();
				if ( Schedule_val < 0.6 ) {
					$( '#Schedule,#Schedule_wave,#score' ).addClass( 'red' );
				} else if ( Schedule_val == 1 ) {
					$( '#Schedule,#Schedule_wave,#score' ).addClass( 'green' );
				} else {
					$( '#Schedule,#Schedule_wave,#score' ).addClass( 'blue' );
				}
			}
		}
	}
	Schedule.init();
	//波浪进度条end

	//历史诊断start
	$( '.diagnose_tag' ).mouseenter( function() {
		$( this ).next( '.diagnose_list' ).show();
	} );
	$( '.diagnose_list' ).mouseenter( function() {
		$( this ).show();
	} );
	$( '.diagnose_tag' ).mouseleave( function() {
		$( this ).next( '.diagnose_list' ).hide();
	} );
	$( '.diagnose_list' ).mouseleave( function() {
		$( this ).hide();
	} );
	//历史诊断end

	//立即诊断
	$( '.diag_immediately input' ).click( function() {
		var search_kwds = $( '#diag_search input[type=text]' ).val(),
			search_indus = $( '#diag_search .button span' ).text(),
			search_value = $( '#diag_search .button span' ).prop( 'class' );
		if ( search_kwds == '' ) {
			ShowTitleMessage.showWarning( '请输入标题内容！', showTime );
			return;
		}
		if ( $( '#diag_search .button' ).text() == '适合的行业' ) {
			ShowTitleMessage.showWarning( '请选择行业！', showTime );
			return;
		}
		var state = {
			search_kwds: search_kwds,
			search_indus: search_indus,
			search_value: search_value
		};
		history.replaceState( state, document.title, '/TitleDiagnose/result?keywords=' + search_kwds + '&industry=' + search_indus + '&value=' + search_value );
		_search.options.title = search_kwds;
		_search.options.cc = search_value;
		_search.init();
	} );
	//获取数据start
	var _keywords = getUrlParam( 'keywords' ),
		_industry = getUrlParam( 'industry' ),
		_value = getUrlParam( 'value' );
	var history_arr = [];
	var _search = {
		options: {
			title: _keywords,
			cc: _value
		},
		init: function() {
			ShowTitleMessage.show( '正在分析' );
			$('.analysis_words').removeClass('analy_blue analy_red');
			$( 'body' ).css( {
				'overflow': 'hidden',
				'padding-right': 17
			} );
			var _this = this;
			$.ajax( {
				type: "post",
				dataType: "json",
				url: thisApis.GET_RESULT,
				data: this.options,
				success: function( data ) {
					$( '.diag_result .diag_result_cont' ).show();
					$( '.diag_result .no_content' ).hide();
					ShowTitleMessage.hide();
					$( 'body' ).css( {
						'overflow': 'auto',
						'padding-right': 0
					} );
					//总分
					var result_data = data.data,
						_score = result_data.score;
					_score = Math.floor( _score )
					Schedule.start( _score / 100 );
					//柱状图
					var lengthScore=result_data.lengthScore,
						patternScore=result_data.patternScore,
						keywordScore=result_data.keywordScore,
						hotTopicScore=result_data.hotTopicScore,
						impactScore=result_data.impactScore;
					if(lengthScore==0){
						$( '.analysis_words', '.changdu' ).addClass( 'analy_red' );
					}else if(lengthScore==100){
						$( '.analysis_words', '.changdu' ).addClass( 'analy_blue' );
					}
					if(patternScore==0){
						$( '.analysis_words', '.sentence' ).addClass( 'analy_red' );
					}else if(patternScore==100){
						$( '.analysis_words', '.sentence' ).addClass( 'analy_blue' );
					}
					if(keywordScore==0){
						$( '.analysis_words', '.keyword' ).addClass( 'analy_red' );
					}else if(keywordScore==100){
						$( '.analysis_words', '.keyword' ).addClass( 'analy_blue' );
					}
					if(hotTopicScore==0){
						$( '.analysis_words', '.hotspot' ).addClass( 'analy_red' );
					}else if(hotTopicScore==100){
						$( '.analysis_words', '.hotspot' ).addClass( 'analy_blue' );
					}
					if(impactScore==0){
						$( '.analysis_words', '.effect' ).addClass( 'analy_red' );
					}else if(impactScore==100){
						$( '.analysis_words', '.effect' ).addClass( 'analy_blue' );
					}
					var column_chart = echarts.init( document.getElementById( 'column_chart' ) );
					var column_option = {
						color: [ '#3398DB' ],
						tooltip: {
							trigger: 'axis',
							axisPointer: { // 坐标轴指示器，坐标轴触发有效
								type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
							}
						},
						grid: {
							left: 'left',
							top: '5',
							right: '0',
							bottom: '0',
							containLabel: true
						},
						xAxis: [ {
							type: 'category',
							data: [ '长度', '句型', '关键词', '热点', '影响力' ],
							axisTick: {
								alignWithLabel: true
							}
						} ],
						yAxis: [ {
							type: 'value'
						} ],
						series: [ {
							name: '分数',
							type: 'bar',
							barWidth: '30%',
							data: [ lengthScore, patternScore, keywordScore, hotTopicScore, impactScore ]
						} ],
					};
					column_chart.setOption( column_option );
					//违规图标
					if ( result_data.UnrulyScore != 0 ) {
						$( '#weigui' ).addClass( 'weigui_true' );
						$( '.analysis_words', '.deregulation' ).addClass( 'analy_red' );
					} else {
						$( '#weigui' ).removeClass( 'weigui_true' );
						$( '.analysis_words', '.deregulation' ).addClass( 'analy_blue' );
					}
					//长度分析
					var changdu_text = result_data.lengthAdvise,
						changdu_num = result_data.length;
					$( '.analysis_words', '.changdu' ).text( changdu_text );
					$( '.num', '.changdu' ).text( changdu_num );
					//句型分析
					var sentence_text = result_data.patternMsg,
						sentence_match=result_data.patternSize;
					$( '.analysis_words', '.sentence' ).text( sentence_text );
					$( '.analy_result', '.sentence' ).text( sentence_match );
					//关键词分析
					var commonPercent = result_data.commonPercent,
						emotionPercent = result_data.emotionPercent,
						newPercent = result_data.newPercent,
						powerPercent = result_data.powerPercent,
						commontKeyWord=result_data.commontKeyWord,
						newKeyWord=result_data.newKeyWord,
						emotionKeyWord=result_data.emotionKeyWord,
						powerKeyWord=result_data.powerKeyWord,
						keyword_text=result_data.keyWordMsg;
					$('.analysis_words','.keyword').text(keyword_text);
					$( '.keyword_chart dd:nth-child(1) .percent' ).text( Number(commonPercent)*100+'%' );
					$( '.keyword_chart dd:nth-child(2) .percent' ).text( Number(newPercent)*100+'%' );
					$( '.keyword_chart dd:nth-child(3) .percent' ).text( Number(emotionPercent)*100+'%' );
					$( '.keyword_chart dd:nth-child(4) .percent' ).text( Number(powerPercent)*100+'%' );
					$( '.keyword_chart dd:nth-child(1) .keyword_wz' ).text( commontKeyWord );
					$( '.keyword_chart dd:nth-child(2) .keyword_wz' ).text( newKeyWord );
					$( '.keyword_chart dd:nth-child(3) .keyword_wz' ).text( emotionKeyWord );
					$( '.keyword_chart dd:nth-child(4) .keyword_wz' ).text( powerKeyWord );
					var pie_chart = echarts.init( document.getElementById( 'pie_chart' ) );
					var pie_option = {
						tooltip: {
							trigger: 'item',
							formatter: "{b}: {d}%"
						},
						series: [ {
							name: '关键词',
							type: 'pie',
							radius: [ '70%', '100%' ],
							avoidLabelOverlap: false,
							hoverAnimation: false,
							color: [ '#d2d2d2', '#f4ad04', '#38c746', '#5e83f8' ],
							label: {
								normal: {
									show: false,
									position: 'center'
								},
								emphasis: {
									show: true,
									textStyle: {
										fontSize: '14'
									}
								}
							},
							labelLine: {
								normal: {
									show: false
								}
							},
							data: [ {
								value: Number(commonPercent)*100,
								name: '常见词'
							}, {
								value: Number(newPercent)*100,
								name: '新词'
							}, {
								value: Number(emotionPercent)*100,
								name: '情感词'
							}, {
								value: Number(powerPercent)*100,
								name: '能量词'
							}, ]
						} ]
					};
					pie_chart.setOption( pie_option );
					//热点分析
					var hotspot_text = result_data.hotTopicMsg,
						hotspot_match=result_data.hotTopic[0]||'';
					$( '.analysis_words', '.hotspot' ).text( hotspot_text );
					$( '.analy_result', '.hotspot' ).text( hotspot_match );
					//影响力分析
					var effect_text = result_data.impactMsg,
						effect_match=result_data.impactWords;
					$( '.analysis_words', '.effect' ).text( effect_text );
					$( '.analy_result', '.effect' ).text( effect_match );
					//违规分析
					var deregulation_text = result_data.UnrulyScoreMsg,
						deregulation_match=result_data.UnrulyWords;
					$( '.analysis_words', '.deregulation' ).text( deregulation_text );
					$( '.analy_result', '.deregulation' ).text( deregulation_match );
					//数据存储
					var history_obj = {},
						history_html = '';
					history_obj.title = _this.options.title;
					history_obj.score = _score;
					history_arr.push( history_obj );
					for ( var i in history_arr ) {
						history_html += '<li class="clearfix">' +
							'<p class="words fl">' + history_arr[ i ].title + '</p>' +
							'<div class="num fr">' + history_arr[ i ].score + '</div>' +
							'</li>'
					}
					$( '.diagnose_list .no_content' ).hide();
					$( '.diagnose_list ul' ).empty().append( history_html );

				}
			} );
		}

	}
	if ( _keywords != null ) {
		$( '#diag_search input[type=text]' ).val( _keywords );
		$( '#diag_search .button' ).html( '<span class="' + _value + '">' + _industry + '</span>' );
		_search.init();
	}
	//获取数据end

} );